// 优惠券
"use strict";
const Service = require("egg").Service;
const { Op } = require("sequelize");
const { failRes, successRes } = require("../extend/helper");
const { Journal } = require("../exception/Journal");
function toInt(str) {
  if (typeof str === "number") return str;
  if (!str) return str;
  return parseInt(str, 10) || 0;
}
class sCoupons extends Service {
  // 查询所有的优惠券
  async pc_s_query(params) {
    console.log(params, "<========paramsCoupons");
    let response = null;
    const { ctx } = this;
    try {
      const currentPage = toInt(params?.currentPage ?? 1);
      const pageSize = toInt(params?.pageSize ?? 10);
      const title = params?.title ?? "";

      const result = await ctx.model.Coupons.findAndCountAll({
        where: {
          title: {
            [Op.like]: `%${title}%`, // 使用 Op.like 实现模糊匹配
          },
          type: {
            [Op.like]: `%${params?.type ?? ""}%`,
          }
        },
        order: [["id", "DESC"]], // 排序
        attributes: ["id", "title", "price", "type", "end_time", "createdAt", "updatedAt"],
        limit: pageSize, // 每页多少条
        offset: pageSize * (currentPage - 1), // 跳过多少条
      });
      console.log(result, "<================couponsResult");

      await Journal(ctx, { operatorType: "优惠券 -> 查询", code: 200 });
      response = successRes({
        records: result?.rows ?? [],
        total: result?.count ?? 0,
        pageSize,
        currentPage,
      });
    } catch (error) {
      console.error(error, "<---- error - 优惠券");
      await Journal(ctx, { operatorType: "优惠券 -> 查询", code: 401 });
      response = failRes(401);
    }
    return response;
  }


  // 查询用户拥有的优惠券
  async wa_s_query_ucoupons(params) {
    console.log(params, "<================wa_s_query_ucoupons");
    let response = null;
    const { ctx } = this;
    let count = 0;

    try {
      count = await ctx.model.UsersCoupons.count({
        where: {
          uid: params?.uid ?? "",
          state:params?.state ?? 0,

        }
      });
      //通过中间表查询其它表数据以及中间表数据！！！！！！！【through】
      response = await ctx.model.Users.findByPk(params?.uid,{
       
        attributes: ["id", "nickName", "userName", "totals"], 
        include: [{
          model: ctx.model.Coupons,
          through: {
            model: ctx.model.UsersCoupons,
            where: {
              state: params?.state ?? 0,
              uid: params?.uid ?? "",
              // id:  {
              //   // 子查询：检索重复的 id
              //   [ctx.model.Sequelize.Op.in]: ctx.model.Sequelize.literal(`
              //   SELECT id FROM (SELECT id FROM UsersCoupons WHERE uid = '6' AND state = 0 GROUP BY id HAVING COUNT(id) > 1 ) AS duplicateIds `)
              //   // [ctx.model.Sequelize.Op.in]: ctx.model.Sequelize.literal(`SELECT id FROM ( SELECT id FROM UsersCoupons WHERE uid = '${params?.uid ?? ""}' AND state = ${params?.state ?? 0} GROUP BY id HAVING COUNT(id) > 1) AS duplicateIds`)
              // }
            },
            attributes: ["id", "state", "cid", "uid","createdAt"],
            order: [["createdAt", "DESC"]],
          }
        }],
        
        //根据id分组
        // group: ["UsersCoupons.id"],

      });

      console.log(response, "<---- response - 查询用户拥有的优惠券");

      await Journal(ctx, { operatorType: "用户拥有的优惠券 -> 查询", code: 200 });
      response = successRes({
        // records: response ,
        records: response?.coupons ?? [],
        total: count,
      });
    } catch (error) {
      console.error(error, "<---- error - 查询用户拥有的优惠券");
      await Journal(ctx, { operatorType: "用户拥有的优惠券 -> 查询", code: 401 });
      response = failRes(401);
    }
    return response;
  }

  //用户领取优惠券
  async wa_s_create_usercoupons(params) {
    console.log(params, "<---- params - 用户领取优惠券");
    let response = null;
    const { ctx } = this;
    try {
      await ctx.model.UsersCoupons.create(
        {
          uid: params?.uid ?? "",
          cid: params?.cid ?? "",
          state: params?.state ?? 0,
        },
        { attributes: { extends: ["id", "uid", "cid", "state"] } } // 向数据库插入特定字段
      );
      await Journal(ctx, { operatorType: "用户领取优惠券 -> 新增", code: 200 });
      response = successRes();

    }catch (error) {
      console.error(error, "<---- error - 用户领取优惠券");
      await Journal(ctx, { operatorType: "用户领取优惠券 -> 领取", code: 401 });
      response = failRes(401);
    }
    return response;
  }

  //修改用户拥有的优惠券的状态
  async wa_s_update_usercoupons(params) {
    console.log(params, "<---- params - 修改用户拥有的优惠券的状态");
    let response = null;
    const { ctx } = this;
    try {
      await ctx.model.UsersCoupons.update(params, {
        where: { id: params.id },
        attributes: { extends: ["id", "uid", "cid"] },
      });
      await Journal(ctx, { operatorType: "优惠券 -> 编辑", code: 200 });
      response = successRes();
    }catch (error) {
      console.error(error, "<---- error - 修改用户拥有的优惠券的状态");
      await Journal(ctx, { operatorType: "修改用户拥有的优惠券的状态 -> 修改", code: 401 });
      response = failRes(401);
    }
    return response;
  }




  // 增加优惠券 - 后台管理
  async pc_s_create(params) {
    let response = null;
    const { ctx } = this;
    try {
      await ctx.model.Coupons.create(
        params,
        { attributes: { extends: ["id", "title", "price", "type", "end_time"] } } // 向数据库插入特定字段
      );
      await Journal(ctx, { operatorType: "优惠券 -> 新增", code: 200 });
      response = successRes();
    } catch (error) {
      console.error(error, "<---- error - 优惠券新增");
      await Journal(ctx, { operatorType: "优惠券 -> 新增", code: 401 });
      response = failRes(401);
    }
    return response;
  }

  // 修改优惠券
  async pc_s_update(params) {
    let response = null;
    const { ctx } = this;
    try {
      await ctx.model.Coupons.update(params, {
        where: { id: params.id },
        attributes: { extends: ["id"] },
      });
      await Journal(ctx, { operatorType: "优惠券 -> 编辑", code: 200 });
      response = successRes();
    } catch (error) {
      console.error(error, "<---- error - 优惠券编辑");
      await Journal(ctx, { operatorType: "优惠券 -> 编辑", code: 401 });
      response = failRes(401);
    }
    return response;
  }

  // 删
  async pc_s_delete(params) {
    let response = null;
    try {
      const { ctx } = this;
      await ctx.model.Coupons.destroy({
        where: { id: params.id },
      });
      await Journal(ctx, { operatorType: "优惠券 -> 删除", code: 200 });
      response = successRes();
    } catch (error) {
      console.error(error, "<---- error - 优惠券删除");
      await Journal(ctx, { operatorType: "优惠券 -> 删除", code: 401 });
      response = failRes(401);
    }
    return response;
  }
}

module.exports = sCoupons;
